package bar.dark.lee;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.TextView;
import android.widget.Toast;
import bar.dark.lee.common.BDUtil;
import bar.dark.lee.common.DBSQLite;
import bar.dark.lee.common.DBSQLite.ParseSelectData;
import bar.dark.lee.insert.BalanceQuery;
import bar.dark.lee.manager.card.CreditCardResultDateData;
import bar.dark.lee.manager.money.BankbookData;
import bar.dark.lee.setting.auto.AutoCreditDateData;
import bar.dark.lee.setting.auto.AutoData;
import bar.dark.lee.setting.mybankauto.MyBankAutoData;
import bar.dark.lee.setting.sms.InputData;
import bar.dark.lee.setting.sms.Parser;

public class IntroActivitiy extends SuperActivity
{
	public static final String INTRO_AUTO_DATA = "intro_auto_data";

	public static final String INTRO_MYBANK_AUTO_DATA = "intro_mybank_auto_data";

	private static final int REQUEST_AUTO = 0;
	private static final int REQUEST_MYBANK_AUTO = 1;
	
	public static final String RESULT_AUTO_COUNT = "result_auto_count";
	public static final String RESULT_MYBANK_AUTO_COUNT = "result_mybank_auto_count";

	public static final String RESULT_AUTO_CREATE_DATE_COUNT = "result_auto_create_date_count";

	private DBSQLite dbSql;
	
	private int toYear;
	private int toMonth;
	private int toDay;
	
	private TextView intro_title;
	
	private ArrayList<BankbookData> list;
	
	private Handler mHandler = new Handler() 
	{
		public void handleMessage(Message msg) 
		{
			new DBInitBackground().execute(0);
		}; 
	};
	
	private ArrayList<AutoData> autoList;
	private ArrayList<MyBankAutoData> autoMyBankList;
	private int autoSetting;
	private int autoMyBankSetting;
	
	private int autoTotalCount;
	
	private int autoCreditDateCount;
	
	private int creditResultCount;
	
	private int firstLinkId = -1;
	private int lastLinkId = -1;
	
	@Override
	protected void onCreate(Bundle savedInstanceState)
	{
		isAdFlag = false;
		
		super.onCreate(savedInstanceState);
		
		setContentView(R.layout.intro_activity);
		
		setGoneTitle();
		
		intro_title = (TextView) findViewById(R.id.intro_title);
		intro_title.setText("꿀꿀이 가계부 (v"+ getResources().getString(R.string.app_ver) +")");
		
		Calendar cal = Calendar.getInstance();
    	
    	toYear = cal.get(Calendar.YEAR);
    	toMonth = cal.get(Calendar.MONTH);
    	toDay = cal.get(Calendar.DAY_OF_MONTH);
    	
    	dbSql = DBSQLite.getInstance(IntroActivitiy.this);
    	
    	if (BDConstents.MARKET_TYPE == BDConstents.TSTORE)
		{
    		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
        	
        	int flag = pref.getInt(BDConstents.FIRST_START, 0);
    		
    		if (flag == 0)
    		{
    			AlertDialog.Builder dialog = new AlertDialog.Builder(this);
    			dialog.setTitle("알림");
    			dialog.setMessage("꿀꿀이 가계부는 부채 기능을 위해 개인 주소록의 수집이 필요하며, " +
    					"절대 다른 용도로 사용하지 않습니다.\n" +
    					"꿀꿀이 가계부의 사용을 원하시면 '시작' 을\n" +
    					"사용을 원치 않으시면 '종료' 를 눌러주세요.");
    			dialog.setCancelable(false);
    			dialog.setPositiveButton("시작", new DialogInterface.OnClickListener()
    			{
    				@Override
    				public void onClick(DialogInterface dialogg, int which)
    				{
    					dialogg.dismiss();
    					mHandler.sendEmptyMessageDelayed(0, 1000);
    				}
    			});
    			
    			dialog.setNegativeButton("종료", new DialogInterface.OnClickListener()
    			{
    				@Override
    				public void onClick(DialogInterface dialog, int which)
    				{
    					dialog.dismiss();
    					finish();
    				}
    			});
    			
    			dialog.show();
    		}
    		else
    		{
    			mHandler.sendEmptyMessageDelayed(0, 1000);
    		}
		}
    	else
    	{
    		mHandler.sendEmptyMessageDelayed(0, 1000);
    	}
	}
	
	@Override
	protected void onResume()
	{
		super.onResume();
	}
	
	/**
	 * 인트로에서 백 버튼 막을려고 넣음. 
	 */
	@Override
	public void onBackPressed() 
	{
	}
	
	/**
	 * 메인으로
	 */
	private void goMain() 
	{
		Intent intent = new Intent(IntroActivitiy.this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
		startActivity(intent);
		finish();
		overridePendingTransition(R.anim.right_in, R.anim.left_out);
	}
	
	/**
	 * 카드 결제일 자동결제 확인
	 */
	private void setCreditResultData()
	{
		creditResultCount = 0;
		
		dbSql.selectMapTile(this, "SELECT * FROM credit_card_result_date WHERE autoyn = 1 " +
				"and resultdate >= 0 and resultdate <= " + toDay 
				+ " and signdate <= " + BDUtil.getDateDB(toYear, toMonth+1, 1) + ";", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				ArrayList<CreditCardResultDateData> list = new ArrayList<CreditCardResultDateData>();
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int linknameIdx = c.getColumnIndex("linkname");
				int autoynIdx = c.getColumnIndex("autoyn");
				int startdateIdx = c.getColumnIndex("startdate");
				int enddateIdx = c.getColumnIndex("enddate");
				int resultdateIdx = c.getColumnIndex("resultdate");
				int resultflagIdx = c.getColumnIndex("resultflag");
				int signdateIdx = c.getColumnIndex("signdate");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					CreditCardResultDateData data = new CreditCardResultDateData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setLinkname(c.getString(linknameIdx));
					data.setAutoyn(c.getInt(autoynIdx) + "");
					data.setStartdate(c.getInt(startdateIdx) + "");
					data.setEnddate(c.getInt(enddateIdx) + "");
					data.setResultdate(c.getInt(resultdateIdx) + "");
					data.setResultflag(c.getInt(resultflagIdx) + "");
					data.setSigndate(c.getInt(signdateIdx) + "");
					data.setLinkid(c.getInt(linkidIdx) + "");
					list.add(data);
					
					c.moveToNext();
				}
				
				for (int i = 0; i < list.size(); i++)
				{
					CreditCardResultDateData data = list.get(i);
					
					setCreditCardResultData(data);
				}
			}
		});
	}
	
	private void setCreditCardResultData(CreditCardResultDateData data)
	{
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		String signDate = data.getSigndate();
		
		int [] toDateArr = BDUtil.getDateSet(toDate);
		int [] signDateArr = BDUtil.getDateSet(signDate);
		
		int tempYear = toDateArr[0] - signDateArr[0];
		int tempMonth = toDateArr[1] - signDateArr[1];
		
		tempMonth = (tempYear * 12) + tempMonth;
		
		int firstMonth = 0;
		
		for (int j = tempMonth-1; j >= firstMonth; j--)
		{
			setInsertCreditResultData(data, j);
		}
		
//		if (tempMonth > 0)
//		{
//			setUpdateCreditDate(data);
//		}
	}
	
	/**
	 * credit_card_result_date 테이블의 마지막 이체 저장 날짜를 갱신한다.
	 * @param id
	 */
	private void setUpdateCreditDate(CreditCardResultDateData data, int year, int month, int day)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("signdate", BDUtil.getDateDB(year, month, day));
		
		String [] whereArgs = new String[]{data.getId()};
		
		dbSql.update(this, "credit_card_result_date", map, "id = ?", whereArgs);
	}
	
	private int rYear = 0;
	private int rMonth = 0;
	private int rDay = 0;
	
	private void setInsertCreditResultData(final CreditCardResultDateData data, int j)
	{
		Calendar cal = Calendar.getInstance();
		
		for (int i = 0; i < j+1; i++)
		{
//			cal.roll(Calendar.MONTH, false);
			cal.add(Calendar.MONTH, -1);
		}
		
		int sYear = cal.get(Calendar.YEAR);
		int sMonth = cal.get(Calendar.MONTH)+1;
		int sDay = Integer.parseInt(data.getStartdate());
				
		int eYear = cal.get(Calendar.YEAR);
		int eMonth = cal.get(Calendar.MONTH)+1;
		int eDay = Integer.parseInt(data.getEnddate());
		
		if (sDay != 1)
		{
			if (data.getResultflag().equals("1"))
			{
				if (cal.get(Calendar.MONTH)+1 == 12)
				{
					eYear++;
					eMonth = 1;
				}
				else
				{
					eMonth++;
				}
			}
			else 
			{
				if (cal.get(Calendar.MONTH)+1 == 1)
				{
					sYear--;
					sMonth = 12;
				}
				else
				{
					sMonth--;
				}
			}
		}
		
		String dbDate = BDUtil.getDateDB(eYear, eMonth, Integer.parseInt(data.getResultdate()));
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		
		if (Integer.parseInt(dbDate) > Integer.parseInt(toDate))
		{
			return;
		}
		
		cal.add(Calendar.MONTH, 1);
		rYear = cal.get(Calendar.YEAR);
		rMonth = cal.get(Calendar.MONTH)+1;
		rDay = cal.get(Calendar.DAY_OF_MONTH);
		
		dbSql.selectMapTile(this, "SELECT postmoney FROM in_out WHERE moneykind = '"
				+ BDUtil.getApostrophe(data.getName()) 
				+ "' and date >= " + BDUtil.getDateDB(sYear, sMonth, sDay)
				+ " and date <= " + BDUtil.getDateDB(eYear, eMonth, eDay) + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				BigDecimal money = BigDecimal.ZERO;
				
				int postmoneyIdx = c.getColumnIndex("postmoney");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					money = money.add(new BigDecimal(c.getString(postmoneyIdx)));
					c.moveToNext();
				}
				
				if (!money.toString().equals("0"))
				{
					HashMap<String, String> map = new HashMap<String, String>();
					
					map.put("category", BDConstents.CATEGORY_POST_OUT);
					
					map.put("outmoney", money.toString());
					
					int day = Integer.parseInt(data.getResultdate());
					String date = "";

					Calendar cal = Calendar.getInstance();
					cal.set(rYear, rMonth-1, day);
					
					if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) >= day)
					{
						date = BDUtil.getDateDB(rYear, rMonth, day);
					}
					else
					{
						date = BDUtil.getDateDB(rYear, rMonth, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
					}
					
					date = BDUtil.getDateDB(rYear, rMonth, Integer.parseInt(data.getResultdate()));
					
					map.put("date", date);
					map.put("moneykind", data.getLinkname());
					map.put("postmoneykind", data.getName());
					map.put("type", BDConstents.BANK_TYPE);
					map.put("memo", data.getName() + " " + BDConstents.CATEGORY_POST_OUT);
					
					dbSql.insert(IntroActivitiy.this, map, "in_out");
					
					// 통장에서 돈을뺀다.
					setBankOutData(data.getLinkname(), money.toString());
					// 신용카드 대금 결제를 한디
					setCreditInData(data.getName(), money.toString());
					
					creditResultCount++;
					
					setUpdateCreditDate(data, rYear, rMonth, rDay);
					
					// 잔액을 입력한다.
					BalanceQuery balace = new BalanceQuery(superContext);
					balace.setBalance(BDConstents.BANK_TYPE, data.getLinkname());
				}
			}
		});
	}

	/**
	 * 자동이체 처리
	 */
	private void setAutoData()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		autoSetting = pref.getInt(BDConstents.AUTO_SETTING, 0);
		
		if (autoSetting == 0)
		{
			setAutoMyBankData();
			return;
		}
		
		dbSql.selectMapTile(this, "SELECT * FROM auto_bank WHERE autodate >= 0 and autodate <= 31;", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				autoList = new ArrayList<AutoData>();
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int categoryIdx = c.getColumnIndex("category");
				int moneyIdx = c.getColumnIndex("money");
				int moneytypeIdx = c.getColumnIndex("moneytype");
				int autodateIdx = c.getColumnIndex("autodate");
				int signdateIdx = c.getColumnIndex("signdate");
				int moneykindIdx = c.getColumnIndex("moneykind");
				int memoIdx = c.getColumnIndex("memo");
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					AutoData data = new AutoData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setCategory(c.getString(categoryIdx));
					data.setMoney(c.getString(moneyIdx));
					data.setMoneytype(c.getInt(moneytypeIdx) + "");
					data.setAutodate(c.getInt(autodateIdx)+ "");
					data.setSigndate(c.getInt(signdateIdx)+ "");
					data.setMoneykind(c.getString(moneykindIdx));
					data.setMemo(c.getString(memoIdx));
					data.setKind(c.getInt(kindIdx) + "");
					
					autoList.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		if (autoSetting == 1)
		{
			new DBInitBackground().execute(1);
			return;
		}
		else if (autoSetting == 2)
		{
			Intent intent = new Intent(IntroActivitiy.this, IntroAutoActivity.class);
			intent.putExtra(INTRO_AUTO_DATA, autoList);
			startActivityForResult(intent, REQUEST_AUTO);
		}
	}
	
	/**
	 *  내통장 자동이체 처리
	 */
	private void setAutoMyBankData()
	{
		SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
		autoMyBankSetting = pref.getInt(BDConstents.AUTO_MYBANK_SETTING, 0);
		
		if (autoMyBankSetting == 0)
		{
			if (autoTotalCount > 0 || creditResultCount > 0 || autoCreditDateCount > 0)
			{
				String message = "";
				
				if (autoTotalCount > 0)
				{
					message = "자동이체가 " + autoTotalCount + "건 ";
				}
				
				if (creditResultCount > 0)
				{
					message += "카드대금처리가 " + creditResultCount + "건 ";
				}
				
				if (autoCreditDateCount > 0)
				{
					message += "할부만료가 " + autoCreditDateCount + "건 ";
				}
				
				message += "처리 되었습니다.";
				
				AlertDialog.Builder builder = new AlertDialog.Builder(IntroActivitiy.this);
				builder.setTitle("알림");
				builder.setMessage(message);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setNegativeButton("확인", new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						goMain();
						dialog.dismiss();
					}
				});
				builder.show();
			}
			else
			{
				goMain();
			}
			
			return;
		}
		
		dbSql.selectMapTile(this, "SELECT * FROM auto_mybank WHERE autodate >= 0 and autodate <= 31;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				autoMyBankList = new ArrayList<MyBankAutoData>();
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int outCategoryIdx = c.getColumnIndex("outcategory");
				int inCategoryIdx = c.getColumnIndex("incategory");
				int moneyIdx = c.getColumnIndex("money");
				int susuMoneyIdx = c.getColumnIndex("susumoney");
				int autodateIdx = c.getColumnIndex("autodate");
				int signdateIdx = c.getColumnIndex("signdate");
				int outkindIdx = c.getColumnIndex("outkind");
				int inkindIdx = c.getColumnIndex("inkind");
				int memoIdx = c.getColumnIndex("memo");
				int kindIdx = c.getColumnIndex("kind");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					MyBankAutoData data = new MyBankAutoData();
					
					data.setId(c.getInt(idIdx) + "");
					data.setName(c.getString(nameIdx));
					data.setOutCategory(c.getString(outCategoryIdx));
					data.setInCategory(c.getString(inCategoryIdx));
					data.setMoney(c.getString(moneyIdx));
					data.setSusuMoney(c.getString(susuMoneyIdx));
					data.setAutodate(c.getInt(autodateIdx) + "");
					data.setSigndate(c.getInt(signdateIdx) + "");
					data.setOutkind(c.getString(outkindIdx));
					data.setInkind(c.getString(inkindIdx));
					data.setMemo(c.getString(memoIdx));
					data.setKind(c.getInt(kindIdx) + "");
					autoMyBankList.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		if (autoMyBankSetting == 1)
		{
			new DBInitBackground().execute(2);
			return;
		}
		else if (autoMyBankSetting == 2)
		{
			Intent intent = new Intent(IntroActivitiy.this, IntroMyBankAutoActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
			intent.putExtra(INTRO_MYBANK_AUTO_DATA, autoMyBankList);
			intent.putExtra(RESULT_AUTO_COUNT, autoTotalCount); 
			intent.putExtra(RESULT_AUTO_CREATE_DATE_COUNT, autoCreditDateCount); 
			startActivityForResult(intent, REQUEST_MYBANK_AUTO);
		}
	}
	
	private void setAutoAllData()
	{
		autoTotalCount = 0;
		autoCreditDateCount = 0;
		
		for (int i = 0; i < autoList.size(); i++)
		{
			AutoData data = autoList.get(i);
			
			setAutoData(data);
		}
	}
	
	private void setMyBankAutoAllData()
	{
		for (int i = 0; i < autoMyBankList.size(); i++)
		{
			MyBankAutoData data = autoMyBankList.get(i);
			
			setMyBankAutoData(data);
		}
	}

	private void setAutoData(AutoData data)
	{
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		String signDate = data.getSigndate();
		
		int [] toDateArr = BDUtil.getDateSet(toDate);
		int [] signDateArr = BDUtil.getDateSet(signDate);
		
		int tempYear = toDateArr[0] - signDateArr[0];
		int tempMonth = toDateArr[1] - signDateArr[1];
		
		tempMonth = (tempYear * 12) + tempMonth;
		
		int firstMonth = 0;
		
		// 할부일경우 체크
		if (data.getKind().equals("2"))
		{
			firstMonth = setCheckDateCountData(data, tempMonth);
		}
		
		int resultCount = 0;
		
		for (int j = tempMonth-1; j >= firstMonth; j--)
		{
			resultCount = resultCount + setInsertAutoData(data, j);
		}
		
//		// 한번이라도 자동화 처리 하면 사인 데이트를 넣는다.
//		if (resultCount > 0)
//		{
//			setUpdateAutoBank(data);
//		}
	}
	
	private void setMyBankAutoData(MyBankAutoData data)
	{
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		String signDate = data.getSigndate();
		
		int [] toDateArr = BDUtil.getDateSet(toDate);
		int [] signDateArr = BDUtil.getDateSet(signDate);
		
		int tempYear = toDateArr[0] - signDateArr[0];
		int tempMonth = toDateArr[1] - signDateArr[1];
		
		tempMonth = (tempYear * 12) + tempMonth;
		
		int resultCount = 0;
		
		int firstMonth = 0;
		
		for (int j = tempMonth-1; j >= firstMonth; j--)
		{
			resultCount = resultCount + setInsertMyBankAutoData(data, j);
		}
	}
	
	private int setInsertAutoData(AutoData data, int j)
	{
		Calendar cal = Calendar.getInstance();
		
		for (int i = 0; i < j; i++)
		{
//			cal.roll(Calendar.MONTH, false);
			cal.add(Calendar.MONTH, -1);
		}
		
		int dbYear = cal.get(Calendar.YEAR);
		int dbMonth = cal.get(Calendar.MONTH);
		int dbDay = Integer.parseInt(data.getAutodate());
		
		String dbDate = BDUtil.getDateDB(dbYear, dbMonth+1, dbDay);
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		
		if (Integer.parseInt(dbDate) > Integer.parseInt(toDate))
		{
			return 0;
		}
		
		AutoData tempData = new AutoData();
		tempData.setId(data.getId());
		tempData.setName(data.getName());
		tempData.setCategory(data.getCategory());
		tempData.setMoney(data.getMoney());
		tempData.setMoneytype(data.getMoneytype());
		tempData.setAutodate(data.getAutodate());
		tempData.setSigndate(data.getSigndate());
		tempData.setMoneykind(data.getMoneykind());
		tempData.setMemo(data.getMemo());
		tempData.setKind(data.getKind());
		
		String type = "";
		// 지출, 수입 플래그
		int flag = 0;
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", tempData.getCategory());
		
		if (tempData.getMoneytype().equals("1"))
		{
			if (tempData.getKind().equals("1"))
			{
				map.put("type", BDConstents.BANK_TYPE);
				map.put("outmoney", tempData.getMoney());
				
				setBankOutData(tempData);
				
				type = BDConstents.BANK_TYPE;
				flag = 0;
			}
			else if (tempData.getKind().equals("2"))
			{
				map.put("type", BDConstents.CREDIT_TYPE);
				map.put("postmoney", tempData.getMoney());
				
				setCreditOutData(tempData);
				
				type = BDConstents.CREDIT_TYPE;
				flag = 0;
			}
		}
		else if (tempData.getMoneytype().equals("2"))
		{
			map.put("type", BDConstents.BANK_TYPE);
			map.put("inmoney", tempData.getMoney());
			
			setBankInData(tempData);
			
			type = BDConstents.BANK_TYPE;
			flag = 1;
		}
		
		String memo = tempData.getName();
		
		if (signCount!= -1 && monthCount != -1)
		{
			memo = memo + " " + monthCount + "개월 할부중 " + signCount + "회차";
		}
		
		if (tempData.getMemo() != null)
		{
			memo = memo + "\n" + tempData.getMemo();
		}
		
		map.put("memo", memo);
		
		map.put("moneykind", tempData.getMoneykind());
		
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int day = Integer.parseInt(tempData.getAutodate());
		
		String date = "";
		
		if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) >= day)
		{
			date = BDUtil.getDateDB(year, month, day);
		}
		else
		{
			date = BDUtil.getDateDB(year, month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		}
		
		map.put("date", date);
		
		dbSql.insert(this, map, "in_out");
		
		autoTotalCount++;
		
		setUpdateAutoBank(data, year, month, day);
		
		// 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		balace.setBalance(type, tempData.getMoneykind());
		
		return 1;
	}
	
	private int setInsertMyBankAutoData(MyBankAutoData data, int j)
	{
		Calendar cal = Calendar.getInstance();
		
		for (int i = 0; i < j; i++)
		{
//			cal.roll(Calendar.MONTH, false);
			cal.add(Calendar.MONTH, -1);
		}
		
		int dbYear = cal.get(Calendar.YEAR);
		int dbMonth = cal.get(Calendar.MONTH);
		int dbDay = Integer.parseInt(data.getAutodate());
		
		String dbDate = BDUtil.getDateDB(dbYear, dbMonth+1, dbDay);
		String toDate = BDUtil.getDateDB(toYear, toMonth+1, toDay);
		
		if (Integer.parseInt(dbDate) > Integer.parseInt(toDate))
		{
			return 0;
		}
		
		MyBankAutoData tempData = new MyBankAutoData();
		tempData.setId(data.getId());
		tempData.setName(data.getName());
		tempData.setOutCategory(data.getOutCategory());
		tempData.setInCategory(data.getInCategory());
		tempData.setMoney(data.getMoney());
		tempData.setSusuMoney(data.getSusuMoney());
		tempData.setAutodate(data.getAutodate());
		tempData.setSigndate(data.getSigndate());
		tempData.setOutkind(data.getOutkind());
		tempData.setInkind(data.getInkind());
		tempData.setMemo(data.getMemo());
		tempData.setKind(data.getKind());
		
		String type1 = "";
		String type2 = "";
		String moneyKind1 = "";
		String moneyKind2 = "";
		
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("category", tempData.getOutCategory());
		
		String memo = tempData.getName();
		
		if (tempData.getMemo() != null)
		{
			memo = memo + " " + tempData.getMemo();
		}
		
		map.put("memo", memo);
		
		map.put("type", BDConstents.MYBANK_INOUT_TYPE);
		
		if (tempData.getKind().equals("1"))
		{
			map.put("linktype", BDConstents.BANK_TYPE);
			map.put("outmoney", tempData.getMoney());
			
			setBankOutData(tempData.getOutkind(), tempData.getMoney());
			
			type1 = BDConstents.BANK_TYPE;
		}
		else if (tempData.getKind().equals("2"))
		{
			map.put("linktype", BDConstents.CREDIT_TYPE);
			map.put("postmoney", tempData.getMoney());
			
			setCreditOutData(tempData.getOutkind(), tempData.getMoney());
			
			type1 = BDConstents.CREDIT_TYPE;
		}
		
		map.put("moneykind", tempData.getOutkind());
		
		// 돈이 나가는 자산이름
		moneyKind1 = tempData.getOutkind();
		
		int year = cal.get(Calendar.YEAR);
		int month = cal.get(Calendar.MONTH)+1;
		int day = Integer.parseInt(tempData.getAutodate());
		
		String date = "";
		
		// 날짜에 따라서 말일로 할지 아닐지 정한다.
		if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) >= day)
		{
			date = BDUtil.getDateDB(year, month, day);
		}
		else
		{
			date = BDUtil.getDateDB(year, month, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
		}
		
		map.put("date", date);
		
		dbSql.insert(this, map, "in_out");
		
		// 잔액을 입력한다.
		BalanceQuery balace = new BalanceQuery(superContext);
		// 돈이 나가는 내통장이체 잔액 입력
		balace.setBalance(type1, moneyKind1);
		
		dbSql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIndex = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				firstLinkId = -1;
				for (int i = 0; i < c.getCount(); i++)
				{
					firstLinkId = c.getInt(idIndex);
					c.moveToNext();
				}
			}
		});
		
		map.clear();
		
		map.put("category", tempData.getInCategory());
		
		String memo2 = tempData.getName();
		
		if (tempData.getMemo() != null)
		{
			memo2 = memo2 + " " + tempData.getMemo();
		}
		
		map.put("memo", memo2);
		
		map.put("type", BDConstents.MYBANK_INOUT_TYPE);
		map.put("linktype", BDConstents.BANK_TYPE);
		map.put("inmoney", tempData.getMoney());
		
		type2 = BDConstents.BANK_TYPE;
		
		setBankInData(tempData.getInkind(), tempData.getMoney());
		
		map.put("moneykind", tempData.getInkind());
		
		// 돈이 들어가는 자산 이름
		moneyKind2 = tempData.getInkind();
		
		map.put("date", date);
		
		dbSql.insert(this, map, "in_out");
		
		// 돈이 들어오는 내통장이체 잔액 입력
		balace.setBalance(type2, moneyKind2);
		
		dbSql.selectMapTile(this, "SELECT max(id) maxid FROM in_out;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int idIndex = c.getColumnIndex("maxid");
				
				c.moveToFirst();
				lastLinkId = -1;
				for (int i = 0; i < c.getCount(); i++)
				{
					lastLinkId = c.getInt(idIndex);
					c.moveToNext();
				}
			}
		});
		
		if (tempData.getSusuMoney() != null && tempData.getSusuMoney().length() > 0
				&& !tempData.getSusuMoney().equals("0"))
		{
			map.clear();
			
			map.put("category", BDConstents.CATEGORY_SUSUMONEY);
			
			String memo3 = tempData.getName();
			
			if (tempData.getMemo() != null)
			{
				memo3 = memo3 + " " + tempData.getMemo();
			}
			
			map.put("memo", memo3);
			
			map.put("type", BDConstents.MYBANK_INOUT_TYPE);
			
			if (tempData.getKind().equals("1"))
			{
				map.put("linktype", BDConstents.BANK_TYPE);
				map.put("outmoney", tempData.getSusuMoney());
				
				setBankOutData(tempData.getOutkind(), tempData.getSusuMoney());
				
				type2 = BDConstents.BANK_TYPE;
			}
			else if (tempData.getKind().equals("2"))
			{
				map.put("linktype", BDConstents.CREDIT_TYPE);
				map.put("postmoney", tempData.getSusuMoney());
				
				setCreditOutData(tempData.getOutkind(), tempData.getSusuMoney());
				
				type2 = BDConstents.CREDIT_TYPE;
			}
			
			map.put("moneykind", tempData.getOutkind());
			map.put("linkid", firstLinkId + "");
			
			if (cal.getActualMaximum(Calendar.DAY_OF_MONTH) >= day)
			{
				map.put("date", BDUtil.getDateDB(year, month, day));
			}
			else
			{
				map.put("date", BDUtil.getDateDB(year, month, cal.getActualMaximum(Calendar.DAY_OF_MONTH)));
			}
			
			map.put("date", date);
			
			dbSql.insert(this, map, "in_out");
			
			// 수수료 내통장이체 잔액 입력
			balace.setBalance(type1, moneyKind1);
		}
		
		setLinkId();
		
		autoTotalCount++;
		
		// 한번이라도 자동화 처리 하면 사인 데이트를 넣는다.
		setUpdateMyBankAutoBank(data.getId(), year, month, day);
		
		return 1;
	}
	
	private void setLinkId()
	{
		if (firstLinkId < 0)
		{
			return;
		}
		
		if (lastLinkId < 0)
		{
			return;
		}
		
		HashMap<String, String> map1 = new HashMap<String, String>();
		map1.put("linkid", firstLinkId + "");
		String [] whereArgs1 = new String[]{lastLinkId + ""};
		dbSql.update(IntroActivitiy.this, "in_out", map1, "id = ?", whereArgs1);
		
		HashMap<String, String> map2 = new HashMap<String, String>();
		map2.put("linkid", lastLinkId + "");
		String [] whereArgs2 = new String[]{firstLinkId + ""};
		dbSql.update(IntroActivitiy.this, "in_out", map2, "id = ?", whereArgs2);
	}
	
	/**
	 * auto_bank 테이블의 마지막 이체 저장 날짜를 갱신한다.
	 * @param id
	 */
	private void setUpdateAutoBank(AutoData data, int year, int month, int day)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("signdate", BDUtil.getDateDB(year, month, day));
		
		String [] whereArgs = new String[]{data.getId()};
		
		dbSql.update(this, "auto_bank", map, "id = ?", whereArgs);
		
		if (data.getKind().equals("2"))
		{
			setCheckDeleteData(data);
		}
	}
	
	private int creditDateCheckCount = 0;
	/**
	 * 할부 카운트를 체크해서 몇번 빠질 것인지 숫자를 정한다.
	 * @param data 
	 * @param tempMonth 
	 */
	private int setCheckDateCountData(AutoData data, final int tempMonth)
	{
		creditDateCheckCount = 0;
		
		dbSql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					int signcount = Integer.parseInt(dateData.getSigncount());
					int monthcount = Integer.parseInt(dateData.getMonthcount());
					
					if (tempMonth > (monthcount - signcount))
					{
						creditDateCheckCount = tempMonth - (monthcount - signcount);
					}
				}
			}
		});
		
		return creditDateCheckCount;
	}
	
	/**
	 * 할부일경우 할부가 끝나면 데이터를 지워준다.
	 * @param data
	 */
	private void setCheckDeleteData(final AutoData data)
	{
		dbSql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					int monthcount = Integer.parseInt(dateData.getMonthcount());
					int signcount = Integer.parseInt(dateData.getSigncount());
					
					if (signcount >= monthcount)
					{
						String [] whereArgs = new String[]{data.getId()};
						dbSql.delete(IntroActivitiy.this, "auto_bank", "id = ?", whereArgs);
						
						String [] whereArgs2 = new String[]{dateData.getId()};
						dbSql.delete(IntroActivitiy.this, "auto_credit_date", "id = ?", whereArgs2);
						
						autoCreditDateCount++;
					}
				}
			}
		});
	}

	/**
	 * auto_mybank 테이블의 마지막 이체 저장 날짜를 갱신한다.
	 * @param id
	 */
	private void setUpdateMyBankAutoBank(String id, int year, int month, int day)
	{
		HashMap<String, String> map = new HashMap<String, String>();
		
		map.put("signdate", BDUtil.getDateDB(year, month, day));
		
		String [] whereArgs = new String[]{id};
		
		dbSql.update(this, "auto_mybank", map, "id = ?", whereArgs);
	}

	private void setBankInData(final AutoData data)
	{
		dbSql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
				
//				int money = 0;
				
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					
					c.moveToNext();
				}
				
				money = money.add(new BigDecimal(data.getMoney()));
				
//				money = money + Integer.parseInt(data.getMoney());
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
		
		setTotalMoney(true, data);
	}

	private void setBankOutData(final AutoData data)
	{
		dbSql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(data.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
		
		setTotalMoney(false, data);
	}
	
	private void setBankInData(String bankName, final String orgMoney)
	{
		dbSql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(bankName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
				
//				int money = 0;
				
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					
					c.moveToNext();
				}
				
				money = money.add(new BigDecimal(orgMoney));
				
//				money = money + Integer.parseInt(data.getMoney());
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
	}

	/**
	 * 통장에서 돈을 뺀다
	 * @param bankName 통장 이름
	 * @param orgMoney 빠질 금액
	 */
	private void setBankOutData(String bankName, final String orgMoney)
	{
		dbSql.selectMapTile(this, "SELECT id, money FROM bankbook WHERE name = '"
				+ BDUtil.getApostrophe(bankName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money - Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(orgMoney));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "bankbook", map, "id = ?", whereArgs);
			}
		});
	}

	private void setTotalMoney(final boolean isInMoney, final AutoData data)
	{
		dbSql.selectMapTile(this, "SELECT money FROM total_money;", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int moneyIdx = c.getColumnIndex("money");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					c.moveToNext();
				}
				
				if (isInMoney)
				{
//					money = money + Integer.parseInt(data.getMoney());
					money = money.add(new BigDecimal(data.getMoney()));
				}
				else
				{
//					money = money - Integer.parseInt(data.getMoney());
					money = money.subtract(new BigDecimal(data.getMoney()));
				}
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("money", money.toString());
				
				dbSql.update(IntroActivitiy.this, "total_money", map, null, null);
			}
		});
	}
	
	private int monthCount = -1;
	private int signCount = -1;

	private void setCreditOutData(final AutoData data)
	{
		monthCount = -1;
		signCount = -1;
		
		dbSql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(data.getMoneykind()) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.add(new BigDecimal(data.getMoney()));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "credit_card", map, "id = ?", whereArgs);
			}
		});
		
		dbSql.selectMapTile(this, "SELECT * FROM auto_credit_date WHERE linkid ="
				+ data.getId() + ";", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				AutoCreditDateData dateData = null;
				
				int idIdx = c.getColumnIndex("id");
				int nameIdx = c.getColumnIndex("name");
				int monthcountIdx = c.getColumnIndex("monthcount");
				int signcountIdx = c.getColumnIndex("signcount");
				int linkidIdx = c.getColumnIndex("linkid");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					dateData = new AutoCreditDateData();
					
					dateData.setId(c.getInt(idIdx) + "");
					dateData.setName(c.getString(nameIdx));
					dateData.setMonthcount(c.getInt(monthcountIdx) + "");
					dateData.setSigncount(c.getInt(signcountIdx) + "");
					dateData.setLinkid(c.getInt(linkidIdx) + "");
					
					c.moveToNext();
				}
				
				if (dateData != null)
				{
					monthCount = Integer.parseInt(dateData.getMonthcount());
					signCount = Integer.parseInt(dateData.getSigncount()) + 1;
					
					HashMap<String, String> map = new HashMap<String, String>();
					
					int count = Integer.parseInt(dateData.getSigncount()) + 1;
					
					map.put("signcount", count + "");
					
					String [] whereArgs = new String[]{dateData.getId()};
					dbSql.update(IntroActivitiy.this, "auto_credit_date", map
							, "id = ?", whereArgs);
				}
			}
		});
	}
	
	/**
	 * 신용카드에 카드대금을 추가한다.
	 * @param cardName 카드이름
	 * @param orgMoney 추가할금액
	 */
	private void setCreditOutData(String cardName, final String orgMoney)
	{
		dbSql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(cardName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.add(new BigDecimal(orgMoney));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "credit_card", map, "id = ?", whereArgs);
			}
		});
	}
	
	/**
	 * 신용카드에 카드대금 없앤다.
	 * @param cardName 카드이름
	 * @param orgMoney 없앨금액
	 */
	private void setCreditInData(String cardName, final String orgMoney)
	{
		dbSql.selectMapTile(this, "SELECT id, outmoney FROM credit_card WHERE name = '"
				+ BDUtil.getApostrophe(cardName) + "';", new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int id = -1;
//				int money = 0;
				BigDecimal money = new BigDecimal("0");
				
				int idIdx = c.getColumnIndex("id");
				int moneyIdx = c.getColumnIndex("outmoney");
				
				c.moveToFirst();
				for (int i = 0; i < c.getCount(); i++)
				{
					id = c.getInt(idIdx);
//					money = money + Integer.parseInt(c.getString(moneyIdx));
					money = money.add(new BigDecimal(c.getString(moneyIdx)));
					
					c.moveToNext();
				}
				
//				money = money + Integer.parseInt(data.getMoney());
				money = money.subtract(new BigDecimal(orgMoney));
				
				HashMap<String, String> map = new HashMap<String, String>();
				map.put("outmoney", money.toString());
				
				String [] whereArgs = new String[]{id + ""}; 
				
				dbSql.update(IntroActivitiy.this, "credit_card", map, "id = ?", whereArgs);
			}
		});
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		super.onActivityResult(requestCode, resultCode, data);
		
		if (resultCode == Activity.RESULT_OK)
		{
			if (requestCode == REQUEST_AUTO)
			{
				autoTotalCount = data.getIntExtra(RESULT_AUTO_COUNT, 0);
				autoCreditDateCount = data.getIntExtra(RESULT_AUTO_CREATE_DATE_COUNT, 0);
				setAutoMyBankData();
			}
			else if (requestCode == REQUEST_MYBANK_AUTO)
			{
				autoTotalCount = data.getIntExtra(RESULT_AUTO_COUNT, 0);
				
				// 자동이체 한개 없으면 바로 다음으로 넘어간다.
				if (autoTotalCount < 1 && creditResultCount < 1 && autoCreditDateCount < 1)
				{
					goMain();
					return;
				}
				
				String message = "";
				
				if (autoTotalCount > 0)
				{
					message = "자동이체가 " + autoTotalCount + "건 ";
				}
				
				if (creditResultCount > 0)
				{
					message += "카드대금처리가 " + creditResultCount + "건 ";
				}
				
				if (autoCreditDateCount > 0)
				{
					message += "할부만료가 " + autoCreditDateCount + "건 ";
				}
				
				message += "처리 되었습니다.";
				
				AlertDialog.Builder builder = new AlertDialog.Builder(IntroActivitiy.this);
				builder.setTitle("알림");
				builder.setMessage(message);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setNegativeButton("확인", new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						goMain();
					}
				});
				builder.show();
			}
		}
		else 
		{
			if (requestCode == REQUEST_AUTO)
			{
				setAutoMyBankData();
			}
			else if (requestCode == REQUEST_MYBANK_AUTO)
			{
				// 자동이체 한개 없으면 바로 다음으로 넘어간다.
				if (autoTotalCount < 1 && creditResultCount < 1 && autoCreditDateCount < 1)
				{
					goMain();
					return;
				}
				
				String message = "";
				
				if (autoTotalCount > 0)
				{
					message = "자동이체가 " + autoTotalCount + "건 ";
				}
				
				if (creditResultCount > 0)
				{
					message += "카드대금처리가 " + creditResultCount + "건 ";
				}
				
				if (autoCreditDateCount > 0)
				{
					message += "할부만료가 " + autoCreditDateCount + "건 ";
				}
				
				message += "처리 되었습니다.";
				
				AlertDialog.Builder builder = new AlertDialog.Builder(IntroActivitiy.this);
				builder.setTitle("알림");
				builder.setMessage(message);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setNegativeButton("확인", new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						goMain();
					}
				});
				builder.show();
			}
		}
	}
	
	private void setBankBookDetail()
	{
		// 예전에 만든 통장일 경우 디테일 테이블에 강제로 데이터를 셋팅 해준다.
		dbSql.selectMapTile(superContext, "SELECT id, name, money FROM bankbook;", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				list = new ArrayList<BankbookData>();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int moneyIndex = c.getColumnIndex("money");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIndex));
					data.setName(c.getString(nameIndex));
					data.setMoney(c.getString(moneyIndex));
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		// 이전의 통장 디테일 테이블에 잘못 들어간 부분 때문에... 필요없는 데이터를 삭제 해준다.
		for (int i = 0; i < list.size(); i++)
		{
			BankbookData data = list.get(i);
			
			dbSql.selectMapTile(superContext, 
					"SELECT * FROM bankbook_detail WHERE linkid = " + data.getId(), new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int idIdx = c.getColumnIndex("id");
					
					c.moveToFirst();
					
					if (c.getCount() > 1)
					{
						for (int j = 0; j < c.getCount()-1; j++)
						{
							String id = c.getInt(idIdx) + "";
							
							String [] whereArgs = new String[]{id};
							dbSql.delete(superContext, "bankbook_detail", "id = ?", whereArgs);
							
							c.moveToNext();
						}
					}
				}
			});
		}
		
		for (int i = 0; i < list.size(); i++) 
		{
			final BankbookData data = list.get(i);
			
			dbSql.selectMapTile(this, "SELECT id FROM bankbook_detail " +
					"WHERE linkid = " + data.getId() + ";", 
					new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int idIdx = c.getColumnIndex("id");
					
					c.moveToFirst();
					
					int id = -1;
					
					for (int i = 0; i < c.getCount(); i++)
					{
						id = c.getInt(idIdx);
						c.moveToNext();
					}
					
					if (id == -1)
					{
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("name", data.getName());
						map.put("linkid", data.getId());
						map.put("addflag", "0");
						
						// 세부 통장 테이블에 데이터를 셋팅한디.
						dbSql.insert(superContext, map, "bankbook_detail");
					}
				}
			});
		}
	}
	
	private void setCheckCardDetail()
	{
		// 예전에 만든 체크카드일 경우 디테일 테이블에 강제로 데이터를 셋팅 해준다.
		dbSql.selectMapTile(superContext, "SELECT id, name FROM check_card;", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				list = new ArrayList<BankbookData>();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIndex));
					data.setName(c.getString(nameIndex));
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		for (int i = 0; i < list.size(); i++) 
		{
			final BankbookData data = list.get(i);
			
			dbSql.selectMapTile(this, "SELECT id FROM checkcard_detail " +
					"WHERE linkid = " + data.getId() + ";", 
					new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int idIdx = c.getColumnIndex("id");
					
					c.moveToFirst();
					
					int id = -1;
					
					for (int i = 0; i < c.getCount(); i++)
					{
						id = c.getInt(idIdx);
						c.moveToNext();
					}
					
					if (id == -1)
					{
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("name", data.getName());
						map.put("linkid", data.getId());
						
						// 세부 체크카드 테이블에 데이터를 셋팅한디.
						dbSql.insert(superContext, map, "checkcard_detail");
					}
				}
			});
		}
	}
	
	private void setCreditCardDetail()
	{
		// 예전에 만든 신용카드일 경우 디테일 테이블에 강제로 데이터를 셋팅 해준다.
		dbSql.selectMapTile(superContext, "SELECT id, name FROM credit_card;", 
				new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				list = new ArrayList<BankbookData>();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				
				c.moveToFirst();
				
				for (int i = 0; i < c.getCount(); i++)
				{
					BankbookData data = new BankbookData();
					data.setId(c.getString(idIndex));
					data.setName(c.getString(nameIndex));
					
					list.add(data);
					
					c.moveToNext();
				}
			}
		});
		
		for (int i = 0; i < list.size(); i++) 
		{
			final BankbookData data = list.get(i);
			
			dbSql.selectMapTile(this, "SELECT id FROM creditcard_detail " +
					"WHERE linkid = " + data.getId() + ";", 
					new ParseSelectData()
			{
				@Override
				public void resultData(Cursor c)
				{
					int idIdx = c.getColumnIndex("id");
					
					c.moveToFirst();
					
					int id = -1;
					
					for (int i = 0; i < c.getCount(); i++)
					{
						id = c.getInt(idIdx);
						c.moveToNext();
					}
					
					if (id == -1)
					{
						HashMap<String, String> map = new HashMap<String, String>();
						map.put("name", data.getName());
						map.put("linkid", data.getId());
						
						// 세부 신용카드 테이블에 데이터를 셋팅한디.
						dbSql.insert(superContext, map, "creditcard_detail");
					}
				}
			});
		}
	}
	
	private void updateSmsDB()
	{
		getPaySMSData(); 
		
//		for (int i=0; i<mArrayPaySMSData.size(); i++)
//		{
//			String [] whereArgs = new String[]{mArrayPaySMSData.get(i).getId()};
//			dbSql.delete(superContext, "sms", "id = ?", whereArgs);
//		}
		
		for (int i=0; i<mArrayPaySMSData.size(); i++)
		{
			PaySMSData data = mArrayPaySMSData.get(i);
			
			//Parser parser2 = new Parser(data.getMessage());
			
			Parser parser2 = null;
			try {
				parser2 = new Parser(data.getMessage());
			} catch (Exception e)
			{
				//Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
				//return;
				continue;
			} finally
			{
				if (parser2 == null)
				{
					//Toast.makeText(superContext, "문자 분석중에 문제가 생겼습니다. 개발자에게 메일을 보내주세요.", Toast.LENGTH_SHORT).show();
					//return;
					continue;
				}
			}
			
			InputData inputData = new InputData();
			inputData = parser2.messageParsing();
			
			if ( inputData == null ||
					( (inputData.getMemo1() == null) || (inputData.getMemo1().equalsIgnoreCase("")) 
					&& ( (inputData.getMemo2() == null) || (inputData.getMemo2().equalsIgnoreCase("")) )
					&& ( (inputData.getMemo3() == null) || (inputData.getMemo3().equalsIgnoreCase("")) )
					&& ( (inputData.getMemo4() == null) || (inputData.getMemo4().equalsIgnoreCase("")) ) )
					|| !parser2.getAvailable()	  )
			{
				continue;
			}
			
			String [] whereArgs = new String[]{mArrayPaySMSData.get(i).getId()};
			dbSql.delete(superContext, "sms", "id = ?", whereArgs);
			
			HashMap<String, String> map = new HashMap<String, String>();
			map.put("name", inputData.getName());
			map.put("address", data.getAddress());
			map.put("message", data.getMessage());
			map.put("messagecardname", inputData.getName());
			map.put("linkcardname", data.getLinkcardname());
			map.put("linkcardtype", data.getLinkcardtype());
			map.put("parser", "1");
			
			dbSql.insert(this, map, "sms");
		}
	}
	
	private ArrayList<PaySMSData> mArrayPaySMSData;
	
	/**
	 * 결제문자정보 데이터 가져온다
	 */
	private void getPaySMSData() {
		
		mArrayPaySMSData = new ArrayList<PaySMSData>();
		
		String query = "";
		
		query = "SELECT * FROM sms"; 
		
		dbSql.selectMapTile(this, query, new ParseSelectData()
		{
			@Override
			public void resultData(Cursor c)
			{
				int count = c.getCount();
				c.moveToFirst();
				
				int idIndex = c.getColumnIndex("id");
				int nameIndex = c.getColumnIndex("name");
				int addressIndex = c.getColumnIndex("address");
				int messageIndex = c.getColumnIndex("message");
				int parserIndex = c.getColumnIndex("parser");
				int messagecardnameIndex = c.getColumnIndex("messagecardname");
				int linkcardnameIndex = c.getColumnIndex("linkcardname");
				int linkcardtypeIndex = c.getColumnIndex("linkcardtype");
				
				for (int i = 0; i < count; i++)
				{
					PaySMSData data = new PaySMSData();
					data.setId(c.getInt(idIndex) + "");
					data.setName(c.getString(nameIndex) + "");
					data.setAddress(c.getString(addressIndex));
					data.setMessage(c.getString(messageIndex));
					data.setParser(c.getString(parserIndex));
					data.setMessagecardname(c.getString(messagecardnameIndex));
					data.setLinkcardname(c.getString(linkcardnameIndex));
					data.setLinkcardtype(c.getString(linkcardtypeIndex));
					
					mArrayPaySMSData.add(data);
					c.moveToNext();
				}
			}
		});
	}
	
	private class PaySMSData
	{
		private String id;
		private String name;
		private String address;
		private String message;
		private String parser;
		private String messagecardname;
		private String linkcardname;
		private String linkcardtype;
		
		public String getId() {
			return id;
		}
		public void setId(String id) {
			this.id = id;
		}
		public String getName() {
			return name;
		}
		public void setName(String name) {
			this.name = name;
		}
		public String getAddress() {
			return address;
		}
		public void setAddress(String address) {
			this.address = address;
		}
		public String getMessage() {
			return message;
		}
		public void setMessage(String message) {
			this.message = message;
		}
		public String getParser() {
			return parser;
		}
		public void setParser(String parser) {
			this.parser = parser;
		}
		public String getMessagecardname() {
			return messagecardname;
		}
		public void setMessagecardname(String messagecardname) {
			this.messagecardname = messagecardname;
		}
		public String getLinkcardname() {
			return linkcardname;
		}
		public void setLinkcardname(String linkcardname) {
			this.linkcardname = linkcardname;
		}
		public String getLinkcardtype() {
			return linkcardtype;
		}
		public void setLinkcardtype(String linkcardtype) {
			this.linkcardtype = linkcardtype;
		}
	}
	
	/**
	 * 디비 초기화 
	 * @author hyojun
	 */
	private class DBInitBackground extends AsyncTask<Integer, Integer, Integer>{
		ProgressDialog dialog = null;
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			dialog = new ProgressDialog(IntroActivitiy.this);
			dialog.setCancelable(false);
			dialog.setCancelable(false);
			dialog.setMessage("Loading...");
			dialog.show();
		}
		
		@Override
		protected Integer doInBackground(Integer... arg0) {
			
			if (arg0[0] == 0)
			{
				DBInit init = new DBInit(IntroActivitiy.this);
				init.setTable(IntroActivitiy.this);
				
				try {
					
					SharedPreferences pref = getSharedPreferences("pref", Activity.MODE_PRIVATE);
			    	int noticeFlag = pref.getInt(BDConstents.NOTICE_FLAG, 0);
			    	
			    	if (noticeFlag < BDConstents.NOTICE_REVISION)
			    	{
						setBankBookDetail();
						
						setCheckCardDetail();
						
						setCreditCardDetail();
						
						updateSmsDB();
			    	}
				} catch (Exception e) {
				}
				
				// 신용카드 결제일 자동이체 
				setCreditResultData();
				
				return 0;
			}
			else if (arg0[0] == 1)
			{
				setAutoAllData();
				return 1;
			}
			else if (arg0[0] == 2)
			{
				setMyBankAutoAllData();
				return 2;
			}
			
			return null;
		}

		@Override
		protected void onPostExecute(Integer result) {
			super.onPostExecute(result);
			if (dialog != null)
			{
				dialog.dismiss();
				dialog = null;
			}
			
			if (result == 0)
			{
				setAutoData();
			}
			else if (result == 1)
			{
				setAutoMyBankData();
			}
			else if (result == 2)
			{
				// 자동이체 한개 없으면 바로 다음으로 넘어간다.
				if (autoTotalCount < 1 && creditResultCount < 1 && autoCreditDateCount < 1)
				{
					goMain();
					return;
				}
				
				String message = "";
				
				if (autoTotalCount > 0)
				{
					message = "자동이체가 " + autoTotalCount + "건 ";
				}
				
				if (creditResultCount > 0)
				{
					message += "카드대금처리가 " + creditResultCount + "건 ";
				}
				
				if (autoCreditDateCount > 0)
				{
					message += "할부만료가 " + autoCreditDateCount + "건 ";
				}
				
				message += "처리 되었습니다.";
				
				AlertDialog.Builder builder = new AlertDialog.Builder(IntroActivitiy.this);
				builder.setTitle("알림");
				builder.setMessage(message);
				builder.setIcon(android.R.drawable.ic_dialog_info);
				builder.setNegativeButton("확인", new OnClickListener()
				{
					@Override
					public void onClick(DialogInterface dialog, int which)
					{
						dialog.dismiss();
						goMain();
					}
				});
				builder.show();
			}
			//creditAuto();
		}
	}

	@Override
	protected void tipButton()
	{
	}
}
